import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/UI/mykeyboard.dart' as board;
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:magic_car/jiance/papularInspects.dart';
import 'package:magic_car/jiance/start.dart';
import 'package:magic_car/util/galleryphotoview.dart';
import 'package:magic_car/zhanshi/cheyuandetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:date_format/date_format.dart';
//import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class BusinessEditcarPage extends StatefulWidget {
  final String oid;

  BusinessEditcarPage(this.oid);
  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid);
}

class _MyHomePageState extends State<BusinessEditcarPage> {
  String pwdData = '输入车牌';
  bool showkb = false;
  final String oid;
  _MyHomePageState(this.oid);
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  // VoidCallback：没有参数并且不返回数据的回调
  VoidCallback _showBottomSheetCallback;

  // TextEditingController _nametroller = new TextEditingController();
  // TextEditingController _agetroller = new TextEditingController();
  // TextEditingController _mobiletroller = new TextEditingController();
  // TextEditingController _validtroller = new TextEditingController();
  // TextEditingController _idcardtroller = new TextEditingController();
  // TextEditingController _expricetroller = new TextEditingController();
  // TextEditingController _passtroller = new TextEditingController();
  // TextEditingController _confirmpasstroller = new TextEditingController();
  List formList;
  bool agreen = false;
  bool select = false;
  File _image;
  String card_z = '';
  String card_f = '';
  bool select_img = false;
  String status = "";
  List imgs = new List();
  List thumb = [];
  List img_url = new List();
  String failreason = "";

  String MIN_DATETIME = '1900-01-01';
  String MAX_DATETIME = '2025-01-01';
  String INIT_DATETIME = '2020-05-01';

  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;
//DateTimePickerLocale _locale = Locale('zn');
  List<DateTimePickerLocale> _locales = DateTimePickerLocale.values;

  String _format = 'yyyy-MMMM';
  TextEditingController _formatCtrl = TextEditingController();

  DateTime _dateTime;

  String current_brand = "";
  String current_type = "";

  Map orderinfo;
  bool isyishou = false;
  bool isonline = false;

  String carstatus = '0';

  TextEditingController car_num = new TextEditingController();
  TextEditingController car_price = new TextEditingController();
  TextEditingController num_km = new TextEditingController();
  TextEditingController people = new TextEditingController();
  TextEditingController mobile = new TextEditingController();
  TextEditingController address = new TextEditingController();
  TextEditingController desrible = new TextEditingController();

  TextEditingController biaoxianlicheng = new TextEditingController();
  TextEditingController pailiang = new TextEditingController();
  TextEditingController guohucishu = new TextEditingController();
  TextEditingController paizhaodi = new TextEditingController();
  TextEditingController chejia = new TextEditingController();
  initState() {
    super.initState();
    _showBottomSheetCallback = _showBottomSheet;
    formList = [
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 6,
        'bottom': 1.0,
        'value': '',
        'code': '',
        'ctroller': car_num,
        'text_type': 1,
        'max_length': 0
      },
      // {
      //   "title": '上牌日期',
      //   'sub_title': '云A00001',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 2,
      //   'bottom': 1.0,
      //   'value': '请选择日期',
      //   'code': ''
      // },
      {
        "title": '品牌',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 3,
        'bottom': 1.0,
        'value': '请选择品牌',
        'code': '',
        'brand_id': '',
      },
      {
        "title": '车型',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 3,
        'bottom': 1.0,
        'value': '请选择车型',
        'code': '',
        'type_id': ''
      },
      {
        "title": '款式',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 3,
        'bottom': 10.0,
        'value': '请选择款式',
        'code': '',
        'typelist_id': '0',
        'price': '0.00'
      },

      {
        "title": '车价（万）',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 10.0,
        'value': '0.00',
        'code': 'car_price',
        'ctroller': car_price,
        'text_type': 2,
        'max_length': 0,
      },

      {
        "title": '上牌时间',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 2,
        'bottom': 1.0,
        'value': '选择上牌时间',
        'code': 'sp_time',
        // 'ctroller':car_price,
        'text_type': 1,
        'max_length': 0
      },
      {
        "title": '表显里程（万）',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'bxlc',
        'ctroller': biaoxianlicheng,
        'text_type': 2,
        'max_length': 0
      },
      {
        "title": '车架号',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'cj',
        'ctroller': chejia,
        'text_type': 2,
        'max_length': 0
      },
      {
        "title": '排放标准',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 8,
        'bottom': 1.0,
        'value': '',
        'code': 'pfbz',
        'ctroller': car_price,
        'text_type': 1,
        'max_length': 0,
        'item': '国一,国二,国三,国四,国五,国六,国七,其他,未知'
      },
      {
        "title": '排量',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'pl',
        'ctroller': pailiang,
        'text_type': 2,
        'max_length': 0
      },
      {
        "title": '变速箱',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 8,
        'bottom': 1.0,
        'value': '',
        'code': 'bsx',
        // 'ctroller': car_price,
        'text_type': 1,
        'max_length': 0,
        'item': '手动,自动'
      },
      {
        "title": '过户次数',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'ghcs',
        'ctroller': guohucishu,
        'text_type': 1,
        'max_length': 0
      },
      {
        "title": '所在城市',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 10.0,
        'value': '',
        'code': 'pzd',
        'ctroller': paizhaodi,
        'text_type': 2,
        'max_length': 0
      },
      // {
      //   "title": '上架时间',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': 'price',
      //   'ctroller': car_price,
      //   'text_type': 1,
      //   'max_length': 0
      // },

      {
        "title": '联系人',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'contact_people',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
      {
        "title": '联系电话',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'contact_mobile',
        'ctroller': mobile,
        'text_type': 1,
        'max_length': 11
      },
      // {
      //   "title": '地址',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': 'address',
      //   'ctroller':address,
      //   'text_type':2
      // },
      // {
      //   "title": '车型',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 3,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
      {
        "title": '车源封面图片',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 4,
        'bottom': 10.0,
        'value': '',
        'code': ''
      },
      {
        "title": '车源图片(至少上传一张)',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 4,
        'bottom': 10.0,
        'value': '',
        'code': ''
      },
      {
        "title": '车源简介',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 5,
        'bottom': 10.0,
        'value': '',
        'code': 'car_descrble',
        'ctroller': desrible
      },
    ];
    //imgs.add({'url':'''order["status"].toString() != "3"'''}'resource/images/user/upimg.png');
    imgs = [
      {'url': '', 'name': '前脸', 'isupdate': 0},
    ];
    thumb = [
      {'url': '', 'name': '前脸', 'isupdate': 0},
    ];
    loaduserinfo();
    loaddata();
  }

  void _showBottomSheet() {
    print('键盘出现');
    setState(() {
      showkb = true;
    });
    if (pwdData == "输入车牌") {
      setState(() {});
    }
    // new NumberKeyboardActionSheet(name: "1111", controller: car_num);
    setState(() {
      // disable the button  // 禁用按钮
      _showBottomSheetCallback = null;
    });

    /*
      currentState：获取具有此全局键的树中的控件状态
      showBottomSheet：显示持久性的质感设计底部面板
      解释：联系上文，_scaffoldKey是Scaffold框架状态的唯一键，因此代码大意为，
           在Scaffold框架中显示持久性的质感设计底部面板
     */
    _scaffoldKey.currentState
        .showBottomSheet<void>((BuildContext context) {
          /// 将自定义的密码键盘作为其child   这里将回调函数传入
          return new board. MyKeyboard(_onKeyDown, pwdData);
        })
        .closed
        .whenComplete(() {
          if (mounted) {
            setState(() {
              // re-enable the button  // 重新启用按钮
              _showBottomSheetCallback = _showBottomSheet;
            });
          }
        });
  }

  /// 密码键盘的整体回调，根据不同的按钮事件来进行相应的逻辑实现
  void _onKeyDown(board. KeyEvent data) {
    print("删除前车牌：" + pwdData);
// 如果点击了删除按钮，则将密码进行修改
    if (data.isDelete()) {
      if (pwdData != "输入车牌") {
        if (pwdData.length > 0) {
          pwdData = pwdData.substring(0, pwdData.length - 1);
          setState(() {});
        }
      }
      if (pwdData.length == 0) {
        setState(() {
          pwdData = "输入车牌";
        });
      }
    }
// 点击了确定按钮时
    else if (data.isCommit()) {
      print("点击完成");
      setState(() {
        pwdData = pwdData;
        showkb = false;
      });
      Navigator.of(context).pop();
//      if (pwdData.length != 7) {
////        Fluttertoast.showToast(msg: "密码不足6位，请重试", gravity: ToastGravity.CENTER);
//        return;
//      }
      // onAffirmButton();
    }
//点击了数字按钮时  将密码进行完整的拼接
    else {
      if (pwdData.length == 0) {}
      if (pwdData == "输入车牌") {
        setState(() {
          pwdData = "";
        });
      }
      if (pwdData.length < 7) {
        pwdData += data.key;
      }
      if (pwdData.length == 7 || pwdData.length > 7) {
        if (showkb == true) {
          Navigator.of(context).pop();
          setState(() {
            showkb = false;
          });
        }
      }
      setState(() {
        pwdData = pwdData;
      });
    }
  }

  loaduserinfo() async {
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');

    HttpHelper.post(HttpHelper.API_BusinessInfo, (data) async {
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          if (data["info"]["avatar"].length != 0) {
            setState(() {
              // avatar = data["info"]["avatar"];
            });
          }
          var info = data["info"];
          setState(() {
            status = info["status"].toString();
          });
        }
      }
    }, params: map);
  }

  Widget layout() {
    List<Widget> tiles = [];
    Widget content;
    tiles.add(Align(
        alignment: Alignment.centerLeft,
        child: Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
            child: Text('填写基本信息'))));
    for (var item in formList) {
      var type = item["type"];
      if (type == 1) {
        //输入框
        tiles.add(inputWidget(item));
      } else if (type == 2) {
        //时间选择
        tiles.add(dateSelect(item));
      } else if (type == 3) {
        //类型选择
        tiles.add(cartype(item));
      } else if (type == 4) {
        //图片
        tiles.add(uploadImgs(item));
      } else if (type == 5) {
        tiles.add(textarea(item));
      } else if (type == 6) {
        tiles.add(carNuminput(item));
      } else if (type == 8) {
        tiles.add(checkBoxs(item));
      }
    }
    // var btn = new SizedBox(
    //     width: double.infinity,
    //     height: 50,
    //     child: new FlatButton(
    //       child: Text('立即申请入驻'),
    //       textColor: Colors.white,
    //       color: Colors.white,
    //       //color: Color.fromRGBO(27, 182, 251, 1),
    //       onPressed: () {
    //         regist();
    //       },
    //     ));

    var refreshbtn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 10, 20, 0),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: carstatus == "0"
                      ? Color.fromRGBO(200, 200, 200, 1)
                      : Color.fromRGBO(27, 182, 251, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1,
                      color: carstatus == "0"
                          ? Color.fromRGBO(200, 200, 200, 1)
                          : Color.fromRGBO(27, 182, 251, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      if (carstatus == "0") return;

                      changeStatus("0");

                      //fresh();
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "下架车源",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));

    var deletebtn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 10, 20, 0),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: carstatus != "0"
                      ? Color.fromRGBO(200, 200, 200, 1)
                      : Color.fromRGBO(27, 182, 251, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1,
                      color: carstatus != "0"
                          ? Color.fromRGBO(200, 200, 200, 1)
                          : Color.fromRGBO(27, 182, 251, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      if (carstatus != "0") return;
                      changeStatus("3");
                      // submit(1);
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "删除车源",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));
    var btn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 20, 20, 10),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: carstatus != "0" && carstatus != "4"
                      ? Color.fromRGBO(200, 200, 200, 1)
                      : Color.fromRGBO(255, 204, 48, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1,
                      color: carstatus != "0" && carstatus != "4"
                          ? Color.fromRGBO(200, 200, 200, 1)
                          : Color.fromRGBO(255, 204, 48, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      if (carstatus != "0" && carstatus != "4") return;
                      submit(0);
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "保存修改",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));

    var applybtn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 20, 20, 10),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: carstatus != "0" && carstatus != "4"
                      ? Color.fromRGBO(200, 200, 200, 1)
                      : Color.fromRGBO(255, 204, 48, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1,
                      color: carstatus != "0" && carstatus != "4"
                          ? Color.fromRGBO(200, 200, 200, 1)
                          : Color.fromRGBO(255, 204, 48, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      if (carstatus != "0" && carstatus != "4") return;
                      changeStatus("1");
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "申请上架",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));

    // if (isyishou == false) {
    //   tiles.add(deletebtn);
    //   tiles.add(btn);
    // }

    // if (isyishou == false && isonline == true) {
    //   tiles.add(refreshbtn);
    // }
    tiles.add(new Row(
      children: <Widget>[
        Expanded(
          child: refreshbtn,
          flex: 1,
        ),
        Expanded(
          child: btn,
          flex: 1,
        ),
      ],
    ));
    tiles.add(new Row(
      children: <Widget>[
        Expanded(
          child: applybtn,
          flex: 1,
        ),
        Expanded(
          child: deletebtn,
          flex: 1,
        ),
      ],
    ));
    if (failreason != "" && carstatus == "4") {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 10, 10),
          child: new Text(
            '驳回原因：${failreason}',
            style: TextStyle(color: Colors.red),
          )));
    }
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 10, 10),
        child: new Text(
          '若需修改车源请先点击“下架车源”确保车源为未上架则可进行修改，修改完成请点击“保存修改” 否则修改无效',
          style: TextStyle(color: Color.fromRGBO(225, 102, 82, 1)),
        )));

    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
        child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }

  //更改车源状态
  changeStatus(status) {
    FocusScope.of(context).requestFocus(FocusNode());

    Map<String, String> param = new Map();
    param['id'] = this.oid;
    param['status'] = status;

    HttpHelper.post(HttpHelper.API_ChangeCarStatus, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          Toast.show('修改成功', context);
          setState(() {
            imgs = [
              {'url': '', 'name': '前脸', 'isupdate': 0},
            ];
            thumb = [
              {'url': '', 'name': '前脸', 'isupdate': 0},
            ];
          });
          // Navigator.pop(context);
          loaddata();
          // Navigator.pop(context);
        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: param);
  }

  Widget checkBoxs(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                  color: Colors.white,
                  height: 50,
                  child: new Row(children: <Widget>[
                    Expanded(
                      child: new Padding(
                        padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                        child: RichText(
                          text: TextSpan(
                              text: item["title"],
                              style: TextStyle(
                                  fontSize: 15,
                                  color: Color.fromRGBO(102, 102, 102, 1)),
                              children: [
                                // TextSpan(
                                //     text: '*',
                                //     style: TextStyle(fontSize: 14, color: Colors.red))
                              ]),
                        ),
                      ),
                      flex: 1,
                    ),
                    Expanded(
                      child: new Padding(
                          padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                          child: Align(
                            alignment: Alignment.centerRight,
                            child: RichText(
                              text: TextSpan(
                                  text: item["value"],
                                  style: TextStyle(
                                      fontSize: 15,
                                      color: Color.fromRGBO(102, 102, 102, 1)),
                                  children: [
                                    // TextSpan(
                                    //     text: '*',
                                    //     style: TextStyle(fontSize: 14, color: Colors.red))
                                  ]),
                            ),
                          )),
                      flex: 1,
                    ),
                  ])),
              checkBox(item)
            ]));
    return content;
  }

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;
    print(item);

    List<String> items = item["item"].split(',');
    print('----');

    String defaultv = items[0];
    // if(this.type==2){
    if (select == false) {
      if (item.containsKey("value") == false) {
        item['value'] = defaultv;
      }
    }
    //}//车商设置选项默认值
    for (var i = 0; i < items.length; i++) {
      tiles.add(Container(
          child: Wrap(children: <Widget>[
        Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
            child: SizedBox(
                width: 22,
                child: Radio<String>(
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    //当前Radio的值
                    hoverColor: Color.fromRGBO(200, 200, 200, 1),
                    focusColor: Color.fromRGBO(25, 172, 249, 1),
                    value: items[i],
                    activeColor: Color.fromRGBO(25, 172, 249, 1),
                    groupValue: item['value'],
                    // groupValue: defaultv,
                    onChanged: (value) {
                      if (i != 0 && item['post_id'] != '3000') {
                        setState(() {
                          select = true;
                          // defaultv = value;
                          item['temp_mustimg'] = '1';
                        });
                      } else {
                        setState(() {
                          item['temp_mustimg'] = '0';
                        });
                      }
                      setState(() {
                        select = true;
                        // defaultv = value;
                        item['value'] = value;
                      });
                    }))),

        // tiles.add(
        new GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if (i != 0) {
                setState(() {
                  select = true;
                  // defaultv = value;
                  //item['mustimg'] = '1';
                  item['temp_mustimg'] = '1';
                });
              } else {
                setState(() {
                  item['temp_mustimg'] = '0';
                });
              }
              setState(() {
                item["value"] = items[i];
              });
            },
            child: Padding(
                padding: new EdgeInsets.fromLTRB(8, 12, 15, 0),
                child: Text(items[i],
                    style: new TextStyle(
                        fontSize: 11,
                        color: Color.fromRGBO(100, 100, 100, 1)))))
      ])));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  //车牌键盘布局

  Widget carNuminput(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
                _showBottomSheetCallback();
              },
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                    flex: 1,
                  ),
                  Expanded(
                    child: Padding(
                        padding: new EdgeInsets.fromLTRB(10, 0, 30, 0),
                        child:
                            // new GestureDetector(
                            //   onTap: (){
                            //     _showBottomSheetCallback();
                            //   },
                            //   child:
                            Align(
                          alignment: Alignment.centerRight,
                          child:
                              // new GestureDetector(
                              //     child:
                              new Text(pwdData),
                        )),
                    flex: 2,
                  )
                ],
              ),
            )));
    return content;
  }

//加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    //  SharedPreferences pref = await SharedPreferences.getInstance();
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_BussinessOrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          setState(() {
            carstatus = orderinfo['car_status'].toString();
          });
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0) {
              str = orderinfo["car_num"];
            } else if (i == 1) {
              str = orderinfo["brand_string"]['name'];
              item['brand_id'] = orderinfo["brand_string"]['id'];
            } else if (i == 2) {
              str = orderinfo["cartype_string"]['name'];
              item['type_id'] = orderinfo["cartype_string"]['id'];
            } else if (i == 3) {
              str = orderinfo["type_list_name"];
              item['typelist_id'] = orderinfo["type_list_id"];
            }
            // } else if (i == 4) {
            //   str = orderinfo["contact_people"];
            // } else if (i == 5) {
            //   str = orderinfo["contact_mobile"];
            // } else if (i == 7) {
            //   str = orderinfo["car_descrble"];
            // }

            if (item['code'] != "") {
              var code = item['code'];
              str = orderinfo[code];
              if (code == "cj") {
                str = orderinfo['chejia_num'];
              }
              if (str == "") {
                if (code == "sp_time") {
                  str = "请选择时间";
                }
              }
            }

            item["value"] = str;
          }

          List tempImags = this.imgs;

          // for (var i = 0; i < tempImags.length; i++) {
          //   var url = orderinfo['car_thumb'][i];
          //   if (url != '') {
          //     tempImags[i]['url'] = orderinfo['car_thumb'][i];
          //     List temparrStr = orderinfo['car_thumb'][i].split('attachment');
          //     print(temparrStr);
          //     //print(orderinfo['car_thumb'][i].split('attachment'));
          //     tempImags[i]['attachment'] =
          //         temparrStr[1].substring(1, temparrStr[1].length);
          //     tempImags[i]['isupdate'] = '1';
          //   }
          // }
          if (orderinfo['thumb'] != "") {
            Map imgitem = {
              'isupdate': 1,
              'url': orderinfo['thumb'],
              'attachment': ""
            };
            thumb.add(imgitem);
          }
          for (var i = 0; i < orderinfo['car_thumb'].length; i++) {
            var url = orderinfo['car_thumb'][i];
            if (url != '') {
              Map imageitems = {
                'attachment': orderinfo['car_thumb'][i],
                'url': orderinfo['car_thumb'][i],
                'isupdate': 1
              };
              imgs.add(imageitems);
            }
          }

          setState(() {
            thumb = thumb;
            formList = oldlist;
            imgs = imgs;
            pwdData = orderinfo["car_num"];
            car_price.text = orderinfo["car_price"];
            people.text = orderinfo['contact_people'];
            mobile.text = orderinfo['contact_mobile'];
            desrible.text = orderinfo['car_descrble'];
            biaoxianlicheng.text = orderinfo['bxlc'];
            guohucishu.text = orderinfo['ghcs'];
            pailiang.text = orderinfo['pl'];
            paizhaodi.text = orderinfo['pzd'];
            chejia.text = orderinfo["chejia_num"];
            isyishou = orderinfo['yishou'] == '1' ? true : false;
            isonline = orderinfo['is_online'] == "1" ? true : false;

            // orders=data["info"];
          });
          if (orderinfo["failreason"] != null) {
            setState(() {
              failreason = orderinfo["failreason"];
            });
          }
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

//刷新车源
  fresh() {
    Map<String, String> param = new Map();
    param["id"] = this.oid;
    HttpHelper.post(HttpHelper.API_RefreshCar, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          // showAlert(data["info"].toString());
          Toast.show('刷新成功', context);
          Navigator.pop(context);
          //清空输入框
          // car_num.clear();

          // address.clear();
          // car_price.clear();
          // desrible.clear();
          // people.clear();
          // mobile.clear();
          // for(int i =0;i<formList.length;i++){
          //   formList[i]["value"]="";
          // }
          // setState(() {
          //   formList=formList;
          //   imgs=[];
          //  // img_url=[];
          // });

          // imgs.add('resource/images/user/upimg.png');

        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: param);
  }

//车源已售
  yishou() async {}
//提交生成检测订单
  submit(yishou) async {
    FocusScope.of(context).requestFocus(FocusNode());
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    print(this.formList);
    Map<String, String> param = new Map();
    for (var i = 0; i < this.formList.length; i++) {
      var item = this.formList[i];
      if (item["code"] != "") {
        var code = item["code"];
        if (item["value"] == "") {
          Toast.show('请填写完整的信息', context);
          return;
          // break;
        }
        param[code] = item["value"].toString();
      }
    }
    String image_Str = '';
    int isupdate = 0;
    for (var i = 0; i < imgs.length; i++) {
      var item = imgs[i];
      print(item);
      if (item['isupdate'].toString() == "1") {
        isupdate++;
      }

      var tempStr = "";
      if (item.containsKey('attachment')) {
        tempStr = item['attachment'];
      }
      if (i == imgs.length - 1) {
        image_Str = image_Str + tempStr;
      } else
        image_Str = image_Str + tempStr + ',';
    }
    if (isupdate == 0) {
      //请上传图片
      Toast.show('请上传图片', context);
      return;
    }
    param["thumb"] = image_Str;
    param["brand_id"] = formList[1]["brand_id"];
    param["cartype_id"] = formList[2]['type_id'];
    param["car_num"] = pwdData;
    param["type_list_id"] = formList[3]['typelist_id'];
    param["type_list_name"] = formList[3]['value'];
    if (thumb.length > 1) {
      param['thumb_img'] = thumb[1]['url'];
    }
    // param["price"]=formList[1]["value"].toString();
    // param["contact_people"]=formList[2]["value"].toString();
    // param["contact_mobile"]=formList[3]["value"].toString();
    // param["address"]=formList[4]["value"].toString();
    // param["car_descrble"]=formList[6]["value"].toString();

    SharedPreferences pref = await SharedPreferences.getInstance();

    param["oid"] = this.oid;
    if (yishou == 1) {
      param["yishou"] = "1";
    }
    print(param);

    HttpHelper.post(HttpHelper.API_BussinessSuborder, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          // showAlert(data["info"].toString());
          Toast.show('修改成功', context);
          Navigator.pop(context);
          // loaddata();
          // Navigator.pop(context);
          //清空输入框
          // car_num.clear();

          // address.clear();
          // car_price.clear();
          // desrible.clear();
          // people.clear();
          // mobile.clear();
          // for(int i =0;i<formList.length;i++){
          //   formList[i]["value"]="";
          // }
          // setState(() {
          //   formList=formList;
          //   imgs=[];
          //  // img_url=[];
          // });

          // imgs.add('resource/images/user/upimg.png');

        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: param);
  }

  showAlert(id) {
    showDialog<Null>(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('您的车源已提交，若完成车况检测将会优先置顶展示'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (_) {
                      return new Papularinspects(id, 2, {}, false);
                    }));
                    //connect();
                    // Navigator.pop(context);
                  },
                  child: new Text(
                    '确定',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }

  //输入框组件
  Widget inputWidget(item) {
    TextInputType texttype = TextInputType.text;
    if (item['text_type'] == 1) {
      texttype = TextInputType.number;
    } else if (item['text_type'] == 2) {
      texttype = TextInputType.text;
    }

    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              item["max_length"] > 0
                  ? Expanded(
                      child: new Padding(
                          padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                          child: new TextField(
                            textAlign: TextAlign.right,
                            controller: item["ctroller"],
                            maxLength: item["max_length"],
                            maxLengthEnforced: true,

                            keyboardType: texttype,
                            //                  inputFormatters: <TextInputFormatter>[
                            //      LengthLimitingTextInputFormatter(20)//限制长度
                            //  ],

                            decoration: InputDecoration(
                              counterText: "",
                              hintText: '请输入' + item["title"],
                              border: OutlineInputBorder(
                                borderSide: BorderSide.none,
                              ),
                            ),
                            onChanged: (val) {
                              setState(() {
                                item["value"] = val;
                              });
                            },
                          )),
                      flex: 2,
                    )
                  : Expanded(
                      child: new Padding(
                          padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                          child: new TextField(
                            textAlign: TextAlign.right,
                            controller: item["ctroller"],

                            keyboardType: texttype,
                            //                  inputFormatters: <TextInputFormatter>[
                            //      LengthLimitingTextInputFormatter(20)//限制长度
                            //  ],

                            decoration: InputDecoration(
                              hintText: '请输入' + item["title"],
                              border: OutlineInputBorder(
                                borderSide: BorderSide.none,
                              ),
                            ),
                            onChanged: (val) {
                              setState(() {
                                item["value"] = val;
                              });
                            },
                          )),
                      flex: 2,
                    )
            ],
          ),
        ));
    return content;
  }

  //日期选择组件
  Widget dateSelect(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                    child: Align(
                        alignment: Alignment.centerRight,
                        child: new GestureDetector(
                            child: new Text(item["value"]),
                            onTap: () async {
                              _showDatePicker(item);
                              // final DateTime dateTime = await showDatePicker(
                              //   context: context,
                              //   //定义控件打开时默认选择日期
                              //   initialDate: initialDate,
                              //   //��义控件最早可以选择的日期
                              //   firstDate: DateTime(2018, 1),
                              //   //定义控件最晚可以选择的日期
                              //   lastDate: DateTime(2050, 1),
                              // );

                              // if (dateTime != null) {
                              //   setState(() {
                              //     String code = item["code"];
                              //     item["value"] = formatDate(
                              //         dateTime, [yyyy, "-", mm, "-", dd]);
                              //     //formalities[code] = item["value"];
                              //   });
                              // }
                            }))),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  void _showDatePicker(item) {
    print('选择日期');
    DatePicker.showDatePicker(
      context,
      onMonthChangeStartWithFirstDate: true,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onChange: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          _dateTime = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          //  String code = item["code"];
          item["value"] = formatDate(dateTime, [yyyy, "-", mm]);
          //formalities[code] = item["value"];
        });
        setState(() {
          _dateTime = dateTime;
        });
      },
    );
  }

  //车辆类型组件
  Widget cartype(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
                //print('选择车型');
                if (item.containsKey("brand_id")) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandSelectRoute(item);
                  })).then((param) {
                    if (current_brand != param['brand_id']) {
                      this.formList[2]['value'] = '请选择车型';
                      this.formList[2]['type_id'] = '';
                      current_type = "";
                    }
                    setState(() {
                      current_brand = param['brand_id'];
                      formList = this.formList;
                    });
                  });
                } else if (item.containsKey("typelist_id")) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new CartypeSelectRoute(
                        item, formList[1]["brand_id"], formList[2]["type_id"]);
                  })).then((param) {
                    print('回传数据');
                    print(param);
                    this.formList[4]['value'] =
                        param['price'].substring(0, param['price'].length - 1);
                    setState(() {
                      formList = this.formList;
                      car_price.text = param['price']
                          .substring(0, param['price'].length - 1);
                    });
                  });
                } else {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new CartypeSelectRoute(
                        item, formList[1]["brand_id"], '0');
                  })).then((param) {
                    if (current_brand != param['type_id']) {
                      this.formList[3]['value'] = '请选择款式';
                      this.formList[3]['typelist_id'] = '';
                      //current_type = "";
                    }
                    setState(() {
                      current_type = param['type_id'];
                      formList = this.formList;
                    });
                  });
                }
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                  //  Expanded(
                  //   child:
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                    child: RichText(
                      text: TextSpan(
                          text: item["value"],
                          style: TextStyle(
                              fontSize: 15,
                              color: Color.fromRGBO(102, 102, 102, 1)),
                          children: [
                            // TextSpan(
                            //     text: '*',
                            //     style: TextStyle(fontSize: 14, color: Colors.red))
                          ]),
                    ),
                  ),

                  //),
                  // Expanded(
                  //   child:
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            'resource/images/user/detail.png',
                            height: 20,
                          ))),

                  // )
                ],
              ),
            )));
    return content;
  }

  //新版图片上传
  Widget uploadImgs(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                                child: buildCImgs(
                                    item["title"] == "车源封面图片" ? thumb : imgs))
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  //图片上传组件
  // Widget imagUp(item) {
  //   Widget content = Padding(
  //       padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
  //       child: Container(
  //         color: Colors.white,
  //         width: double.infinity,
  //         // height: 160,
  //         child: new Column(
  //           mainAxisAlignment: MainAxisAlignment.start,
  //           crossAxisAlignment: CrossAxisAlignment.start,
  //           children: <Widget>[
  //             new Padding(
  //               padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
  //               child: RichText(
  //                 text: TextSpan(
  //                     text: item["title"],
  //                     style: TextStyle(
  //                         fontSize: 15,
  //                         color: Color.fromRGBO(102, 102, 102, 1)),
  //                     children: [
  //                       // TextSpan(
  //                       //     text: '*',
  //                       //     style: TextStyle(fontSize: 14, color: Colors.red))
  //                     ]),
  //               ),
  //             ),
  //             Padding(
  //                 padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
  //                 child: Container(
  //                     color: Colors.white,
  //                     // height: 100,
  //                     child: new Column(
  //                         mainAxisAlignment: MainAxisAlignment.start,
  //                         crossAxisAlignment: CrossAxisAlignment.start,
  //                         children: <Widget>[
  //                           new Container(child: buildCImgs())
  //                         ]))),

  //             //  Expanded(
  //             //   child:
  //           ],
  //         ),
  //       ));
  //   return content;
  // }

  Widget textarea(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                                child: new TextField(
                              maxLines: 10,
                              textAlign: TextAlign.left,
                              controller: item["ctroller"],
                              decoration: InputDecoration(
                                hintText: '请输入' + item["title"],
                                border: OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                ),
                              ),
                              onChanged: (val) {
                                item["value"] = val;
                              },
                            ))
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  List imageModelinspectitem(data) {
    List img_temp = [
      "https://car3.autoimg.cn/cardfs/product/g1/M09/3F/A8/240x180_0_q95_c42_autohomecar__ChwFqV69W4KAf_AzAAShphUBgV4514.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M09/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W32Ad5ehAAT2abQFAio994.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M08/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W3uATe71AASA9ZdptWg816.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M0B/73/06/240x180_0_q95_c42_autohomecar__ChsEmF69W3qAYeneAAQeve0abAo167.jpg",
    ];
    List imgList = List();
    for (int x = 0; x < data.length; x++) {
      GalleryExampleItem item = GalleryExampleItem();
      item.id = '$x';
      item.resource = data[x]['url'];
      // item.resource = data[x]["url"];
      imgList.add(item);
    }
    print(imgList.first.id);

    return imgList;
  }

  Widget buildCImgs(data) {
    List<Widget> tiles = [];

    Widget content;

    List items = data;
    print(items);
    // print('图片数组长度'+items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
            width: 120,
            height: 130,
            // color: Colors.red,
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
                padding: new EdgeInsets.fromLTRB(5, 10, 0, 10),
                child: GestureDetector(
                    onTap: () {
                      if (i == 0) {
                        FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
                        print('点击查看图片');
                        if (data == thumb && thumb.length == 2) {}
                        getImage(data == imgs ? 0 : 1);
                      } else {
                        //查看图片
                        Navigator.of(context).push(new FadeRoute(
                            page: GalleryPhotoViewWrapper(
                          galleryItems: imageModelinspectitem(data),
                          backgroundDecoration: const BoxDecoration(
                            color: Colors.black,
                          ),
                          initialIndex: i,
                        )));
                      }
                    },
                    child: new Column(
                      children: <Widget>[
                        items[i]['isupdate'] == 0
                            ? Image.asset('resource/images/user/upimg.png',
                                width: 100, height: 100)
                            : Stack(children: [
                                Positioned(
                                    //  top:5,
                                    //  bottom: 0,
                                    //  left:0,
                                    //  right: 0,
                                    child: CachedNetworkImage(
                                  imageUrl: items[i]['url'],
                                  width: 100,
                                  height: 100,
                                  fit: BoxFit.cover,
                                )),
                                Positioned(
                                  right: -10,
                                  top: -10,
                                  child: IconButton(
                                      onPressed: () {
                                        if (data == imgs) {
                                          imgs.removeAt(i);
                                          setState(() {
                                            imgs = imgs;
                                          });
                                        } else {
                                          thumb.removeAt(i);
                                          setState(() {
                                            thumb = thumb;
                                          });
                                        }
                                      },
                                      icon: Icon(Icons.delete,
                                          color: Colors.red)),
                                )
                               
                              ]),

                        //Image.network(items[i]['url'], width: 100, height: 100),
                        // Center(child: Text(items[i]['name']))
                      ],
                    )))));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
//   //选择图片
//   getimgs(type, card) async {
//     if (type == 1) {
//       var image = await ImagePicker.pickImage(source: ImageSource.gallery);

//       setState(() {
//         _image = image;
//         select_img = true;
//       });
//     } else {
//       var image = await ImagePicker.pickImage(source: ImageSource.camera);

//       setState(() {
//         _image = image;
//         select_img = true;
//       });
//     }
//     if (_image == null) return;
//     Map<String, String> map = new Map();

//     HttpHelper.upLoadImage(_image, (data) {
//       if (card == 1) {
//         setState(() {
//           card_z = data["url"];
//         });
//       } else {
//         card_f = data["url"];
//       }
//     }, params: map);
//   }

// //选择图片�����
//   Future getImage(type) async {
//     showDialog(
//         context: context,
//         builder: (BuildContext context) {
//           return new SimpleDialog(
//             title: new Text('选择'),
//             children: <Widget>[
//               new SimpleDialogOption(
//                 child: new Text('相机'),
//                 onPressed: () {
//                   Navigator.pop(context);
//                   getimgs(0, type);
//                 },
//               ),
//               new SimpleDialogOption(
//                 child: new Text('相册'),
//                 onPressed: () {
//                   Navigator.pop(context);
//                   getimgs(1, type);
//                 },
//               )
//             ],
//           );
//         });
//     // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
//     // //_upLoadImage(image);//上传图片
//     // setState(() {
//     //   _image = image;
//     // });
//   }
//选择图片
  getimgs(type, index) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    File _files = await FlutterNativeImage.compressImage(image.path);

    Map<String, String> map = new Map();
    Map imgitem;
    HttpHelper.upLoadImage(_files, (data) {
      //loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        // imgs.removeLast();
        // imgs.add(data["url"]);
        // imgs[index]['isupdate'] = 1;
        // imgs[index]['url'] = data["url"];
        // imgs[index]['attachment'] = data["attachment"];
        // // img_url[index]=(data["attachment"]);
        // //imgs.add('resource/images/user/upimg.png');
        // setState(() {
        //   imgs = imgs;
        // });
        imgitem = {
          'isupdate': 1,
          'url': data["url"],
          'attachment': data["attachment"]
        };
        if (index == 0)
          imgs.add(imgitem);
        else {
          if (thumb.length > 1) {
            thumb.removeLast();
          }
          thumb.add(imgitem);
        }

        // img_url[index]=(data["attachment"]);
        //imgs.add('resource/images/user/upimg.png');
        setState(() {
          imgs = imgs;
          thumb = thumb;
        });
      }
    }, params: map);

    // if (_image == null) return;
    // Map<String, String> map = new Map();
    // HttpHelper.upLoadImage(_image, (data) {
    //   if(data.containsKey('code')){
    //     Toast.show(data['msg'], context);
    //   }else{
    //   setState(() {
    //     avatar = data['url'];
    //   });
    //   uploadAvatar();
    //   }
    // }, params: map);
  }

//选择图片方式
  Future getImage(i) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text('相机'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(0, i);
                },
              ),
              new SimpleDialogOption(
                child: new Text('相册'),
                onPressed: () async {
                  Navigator.pop(context);
                  List<AssetEntity> temp = await AssetPicker.pickAssets(context,
                      maxAssets: i == 0 ? 9 : 1);
                  if (temp != null) {
                    for (var item in temp) {
                      File file = await item.file;
                      print(file.path);
                      Map<String, String> map = new Map();
                      Map imgitem;
                      HttpHelper.upLoadImageNocompress(File(file.path), (data) {
                        // print('data');
                        if (data.containsKey('code')) {
                          Toast.show(data['msg'], context);
                        } else {
                          imgitem = {
                            'isupdate': 1,
                            'url': data["url"],
                            'attachment': data["attachment"]
                          };
                          if (i == 0)
                            imgs.add(imgitem);
                          else {
                            if (thumb.length > 1) {
                              thumb.removeLast();
                            }
                            thumb.add(imgitem);
                          }

                          setState(() {
                            imgs = imgs;
                            thumb = thumb;
                          });
                        }
                      }, params: map);
                    }
                  }
                },
              ),
              // imgs[i]['isupdate'].toString() == "1"
              //     ? new SimpleDialogOption(
              //         child: new Text(
              //           '删除',
              //           style: TextStyle(color: Colors.red),
              //         ),
              //         onPressed: () {
              //           Navigator.pop(context);
              //           List temp = imgs;
              //           temp[i]['isupdate'] = 0;
              //           temp[i]['url'] = '';
              //           temp[i]['attachment'] = '';
              //           setState(() {
              //             imgs = temp;
              //           });
              //         },
              //       )
              //     : new Text('')
            ],
          );
        });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          title: new Text('编辑信息'),
          backgroundColor: Colors.white,
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
                decoration: new BoxDecoration(
                  color: Color.fromRGBO(238, 238, 238, 1),
                ),
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.topCenter,
                          child: new ListView(children: <Widget>[layout()]),
                        ),
                        Align()
                      ],
                    )
                    // new ListView(
                    //   children: <Widget>[buildcontent()],
                    // )),
                    ))));
  }
}
